package com.snopy.concurrency.demo_threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author snopy
 * @version 1.0.0
 * @classname ArrayBlockingQueueTest
 * @description
 * @email 77912204@qq.com
 * @date 2022/02/19 8:32
 */
@Slf4j
public class ArrayBlockingQueueTest {
    private static final ArrayBlockingQueue<Apple> abq = new ArrayBlockingQueue<>(1,false);

    public static void main(String[] args) {
        new Thread(new Producer(abq)).start();
        //new Thread(new Producer(abq)).start();
        new Thread(new Consumer(abq)).start();
        new Thread(new Consumer(abq)).start();
        new Thread(new Consumer(abq)).start();

    }
    static class Apple{
        String name;
        Apple(){
            this.name = "Apple";
        }
    }
    static class Producer implements Runnable{
        ArrayBlockingQueue<Apple> abq;
        Producer(ArrayBlockingQueue<Apple> abq){
            this.abq = abq;
        }
        @Override
        public void run() {
            while (true){
                try {
                    TimeUnit.SECONDS.sleep(5);
                    Produce();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
        private void Produce(){
            Apple e = new Apple();
            try {
                abq.put(e);
                log.info("生产了一个Apple->{}",e);
            } catch (InterruptedException interruptedException) {
                interruptedException.printStackTrace();
            }

        }
    }
    static class Consumer implements Runnable{
        ArrayBlockingQueue<Apple> abq;
        Consumer(ArrayBlockingQueue<Apple> abq){
            this.abq = abq;
        }
        @Override
        public void run() {
            while (true){
                //try {
                    //TimeUnit.SECONDS.sleep(2);
                    consum();
               // } catch (InterruptedException e) {
                    //e.printStackTrace();
                //}
            }
        }
        private void consum(){
            Apple poll = null;
            try {
                poll = abq.take();
                log.info("消费了->{}",poll);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
